using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace roster.Domain
{
	public class SavedVarsRaidFileReader : IRaidFileReader
	{
		private static string m_nameTag = "[\"Name\"] = ";
		private static string m_classTag = "[\"Class\"] = ";
		
		#region IRaidFileReader Members
		
		IEnumerable<IPlayer> IRaidFileReader.ReadFile(string fileName)
		{
			TextReader reader = new StreamReader(new FileStream(fileName, FileMode.Open));
			
			int tagIdx;
			List<string> names = new List<string>();
			List<string> classes = new List<string>();
			
			string curline = reader.ReadLine();
			while (curline != null)
			{
				tagIdx = curline.IndexOf(m_nameTag);
				if (tagIdx != -1)
				{
					int nameStartIndex = tagIdx + m_nameTag.Length + 1;
					int nameEndIndex = curline.IndexOf('"', nameStartIndex);
					if (nameEndIndex == -1)
						throw new Exception(string.Format("Bad saved vars file format in file ({0})", fileName));
					string playerName = curline.Substring(nameStartIndex, nameEndIndex - nameStartIndex);
	
					names.Add(playerName);					
				}
				else
				{
					tagIdx = curline.IndexOf(m_classTag);
					if (tagIdx != -1)
					{
						int classStartIndex = tagIdx + m_classTag.Length + 1;
						int classEndIndex = curline.IndexOf('"', classStartIndex);
						if (classEndIndex == -1)
							throw new Exception(string.Format("Bad saved vars file format in file ({0})", fileName));
						string playerClass = curline.Substring(classStartIndex, classEndIndex - classStartIndex);
						
						classes.Add(playerClass);						
					}
				}
				
				curline = reader.ReadLine();
			}
			
			if (names.Count != classes.Count)
				throw new Exception(string.Format("Bad saved vars file format in file ({0})", fileName));

			List<IPlayer> playerList = new List<IPlayer>();
			for (int i = 0; i < names.Count; i++)
			{
				playerList.Add(new Player(names[i], ClassNameToEnum.GetEnum(classes[i])));
			}

			return playerList;
		}
		
		#endregion
	}
}
